写在前面的话

该功能是由Chow Bill[1]基于Chic主题[2]开发的一个搜索功能,由于本人平时想把一些想法、常用的信息搬到博客来,一直苦于没有搜索功能,查找比较麻烦,该功能则大大减少了搜索的时间,对于我来说是非常有用的。在写入该功能过程中遇到了诸多问题,然Chou Bill不仅在他本人的博客中耐心回复,还远程帮我调试了一些问题,在此表示由衷的感谢。

一、基本思路:

  1. search.json
    Git Bash里执行npm install hexo-generator-search生成search.json以包含是文章的基本信息。
  2. html & css
    使用模态框,根据form表单提交后唤出modal,然后进行ajax对search.json进行查询。
  3. 匹配内容和highlight
    根据关键字对文章内容进行匹配,匹配有的加入数组,然后对匹配成功的那些数据进行字符截取并highlight关键字。

二、具体步骤:

  1. 前期准备
  • npm install hexo-generator-search
    Git Bash里执行npm install hexo-generator-search生成search.json
  • jquery(若已加载可略过)
    从官网下载jquery.min.js文件,放入/themes/Chic/source/js/,并在/themes/Chic/下的_config.yml文件里script段添加
    - /js/jquery.min.js
  • 图片
    下载图片(search.png),并将图片放入/themes/Chic/source/image文件夹,在/themes/Chic下的_config.yml文件尾行写入searchImg: /image/search.png
  1. 配置root下的 _config.yml
    将以下代码写入到_config.yml尾行:
1
2
3
4
5
6
# search//please insert in the end of the body
search:
enable: true
path: search.json
field: post
content: true
  1. 添加modal (html和css)
    3.1 html
    在/themes/Chic/layout/下新建文件layout.ejs,写入以下代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<!-- Chic/layout.ejs -->
<div id="u-search">
<div class="modal">
<div class="modal-header">
<div class="container">
<form id="u-search-modal-form" class="u-search-modal-form">
<button type="submit" class="form-submit-btn">
<img src="<%- url_for(theme.searchImg) %>" class="search-btn-img" />
</button>
<input placeholder="搜索文章。。。" class="form-input" id="modal-form-input">
</form>
<a class="modal-close">x</a>
</div>
<div class="search-loading">
<div class="search-loading-bar"></div>
</div>
</div>
<div class="modal-body">
<!-- ul 格式如下 -->
<!-- <ul class="modal-results">
<li class="result-item">
<a class="result-item-detail">
<span class="title">页面配置</span>
<span class="content">
content
</span>
</a>
</li>
</ul> -->
</div>
</div>
<div class="modal-overlay"></div>
</div>

 3.2 css
 在/themes/Chic/source/css/_lib/下新建文件search.css,写入以下代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
#u-search {
display: none;
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
padding: 60px 20px;
z-index: 1001;
}


#u-search .modal {
position: fixed;
height: 80%;
width: 100%;
max-width: 640px;
left: 50%;
top: 0;
margin: 64px 0px 0px -320px;
background: #fff;
z-index: 3;
border-radius: 4px;
overflow: hidden;
}

#u-search .modal-header {
position: relative;
width: 100%;
height: 64px;
z-index: 3;
border-top-left-radius: 4px;
border-top-right-radius: 4px;
font-size: 16px;
box-shadow: 0 1px 2px 0px rgba(0,0,0,0.1);
background: #fff;
transition: all 0.28s ease;
-moz-transition: all 0.28s ease;
-webkit-transition: all 0.28s ease;
-o-transition: all 0.28s ease;
}

#u-search .modal-header .container{
display: flex;
flex-direction: row;
align-items: center;
padding: 0px;
}

#u-search .modal-header .container .u-search-modal-form {
display: flex;
flex-direction: row;
align-items: center;
flex: 1;
}

#u-search .u-search-modal-form .form-submit-btn {
width: 50px;
height: 64px;
background: none;
border: none;
outline: none;
margin: 0 5px 0 5px ;
}

#u-search .u-search-modal-form .form-submit-btn img {
width: 33px;
height: 33px;
}

#u-search .modal-header .container .u-search-modal-form .form-input {
flex: 1;
margin-right: 15px;
border: none;
padding: 10px 10px;
outline: none;
}


#u-search .modal-header .modal-close {
display: block;
width: 55px;
height: 64px;
top: 0;
right: 0;
color: #2196f3;
cursor: pointer;
text-align: center;
line-height: 64px;
vertical-align: middle;
transition: all 0.28s ease;
-moz-transition: all 0.28s ease;
-webkit-transition: all 0.28s ease;
-o-transition: all 0.28s ease;
z-index: 2;
font-size: 22px;
}

#u-search .modal-header .search-loading {
position: absolute;
bottom: 0;
left: 0;
width: 100%;
height: 2px;
background: transparent;
z-index: 1;

}

#u-search .modal-header .search-loading .search-loading-bar {
transition: all 0.28s ease;
-moz-transition: all 0.28s ease;
-webkit-transition: all 0.28s ease;
-o-transition: all 0.28s ease;
position: relative;
display: none;
width: 0%;
height: 100%;
background: #2196f3;

}

#u-search .modal .modal-body {
padding: 15px;
height: calc(100% - 85px);
overflow: auto;

}

#u-search .modal .modal-body::-webkit-scrollbar{
width: 5px;
height: 5px;
/**/
}
#u-search .modal .modal-body::-webkit-scrollbar-track{
background: rgb(239, 239, 239);
border-radius:2px;
}
#u-search .modal .modal-body::-webkit-scrollbar-thumb{
background: #bfbfbf;
border-radius:10px;
}
#u-search .modal .modal-body::-webkit-scrollbar-thumb:hover{
background: #333;
}
#u-search .modal .modal-body::-webkit-scrollbar-corner{
background: #179a16;
}

#u-search .modal .modal-body .modal-results {
list-style: none;
padding-left: 0;
margin: 0px;
}

#u-search .modal .modal-body .modal-results .result-item {
padding: 15px;
}

#u-search .modal .modal-body .modal-results .result-item:hover {
background: #e8f4fd;
}

#u-search .modal .modal-body .modal-results .result-item .result-item-detail {
display: flex;
flex-direction: column;
}

#u-search .modal .modal-body .modal-results .result-item .result-item-detail .title {
color: #6e6e6e;
font-weight: 700;
font-size: 18px;
margin-bottom: 10px;
}

#u-search .modal .modal-body .modal-results .result-item .result-item-detail .content {
display: block;
white-space: inherit;
word-break: break-all;
text-overflow: ellipsis;
font-size: 14px;
color: rgba(85,85,85,0.65);
letter-spacing: 1px;
user-select: none;
}

#u-search .search-keyword {
color: #0c7cd5;
text-decoration: underline;
font-weight: bold;
font-style:normal
}

#u-search .modal-body .no-result {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}

#u-search .modal-overlay {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0,0,0,0.7);
z-index: 1;
}

@media screen and (max-width: 680px) {
#u-search {
padding: 0px;
display: none;
}

#u-search .modal {
box-shadow: none;
max-width: none;
top: 0;
left: 0;
margin: 0;
height: 100%;
border-radius: 0;
}
#u-search .modal-header {
border-radius: 0;
padding: 0px;
}
}

.modal-active {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
}

/* 以下是搜索框 */
.search {
margin-right: 6px;
display: flex;
flex-direction: row;
align-items: center;
}

.search .form-search {
padding: 10px 8px;
}

.search .form-search .input {
display: block;
line-height: 1.3;
color: #555;
background: #e8e8e8;
padding: 5px 8px;
box-shadow: none;
box-sizing: border-box;
font-size: 1rem;
border-radius: 8px;
border: none;
outline: none;
}

.search .search-btn {
width: 22px;
height: 22px;
line-height: 22px;
margin-right: 5px;
}

.search .search-btn .search-btn-img {
height: 100%;
width: 100%;
}


@media screen and (max-width: 479px) {

.navbar-mobile-right {
display: flex;
flex-direction: row;
align-items: center;
}

.search .search-btn {
cursor: pointer;
}

.search .form-search {
display: none;
}

.mobile-search {
position: absolute;
top: 0px;
left: 0px;
right: 50px;
padding-left: 15px;
background: #fff;
height: 80px;
display: flex;
flex-direction: row;
margin-right: 15px;
}

.mobile-search .form-search {
display: block;
flex: 1;
}

.mobile-search .input {
width: 100%;
}
}

p.s. 由于css需要被style.styl引用,故需在/themes/Chic/source/css/style.styl文件首行加入@import “_lib/search.css”

  1. 创建搜索框
    在/themes/Chic/layout/_partial/下新建文件search.ejs,写入以下代码:
1
2
3
4
5
6
7
8
9
10
<% if(config.search && config.search.enable ) { %>
<div class="search ">
<div class="search-btn" onClick="searchToggle()">
<img src="<%- url_for(theme.searchImg) %>" class="search-btn-img" />
</div>
<form class="form-search">
<input class="input" placeholder="Searching" autocomplete="off" id="<%= name %>-search-input"/>
</form>
</div>
<% } %>

p.s. 这里还要提一点,该增加的搜索框会与原页面的排版有冲突,故在此步我们还需要对/themes/Chic/source/css/中的layout.styl修改如下(注意只对.navbar-right进行了修改):

Before After
1
2
3
4
5
6
7
8
9
10
11
.navbar 
height 4rem
line-height 4rem
width 100%
.container
width auto
max-width 1200px
text-align center
margin 0 auto
display flex
justify-content space-between
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
.navbar 
height 4rem
line-height 4rem
width 100%
.container
width auto
max-width 1200px
text-align center
margin 0 auto
display flex
justify-content space-between
.navbar-right
display flex
flex-direction row
align-items center
  1. 将上述步骤4中建立的搜索框添加到header
    打开/themes/Chic/layout/_partial/header.ejs,将下面代码的5-6行,23-27行分别添加到相应位置完成pc和mobile搜索框的添加。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
<nav class="navbar">
<div class="container">
<div class="navbar-header header-logo"><a href="<%- config.root %>"><%= theme.navname %></a></div>
<div class="menu navbar-right">
<% var defaultName = 'pc' %>
<%- partial('_partial/search', { name: defaultName }) %>
<% for (var i in theme.nav){ %>
<a class="menu-item" href="<%- url_for(theme.nav[i]) %>"><%= i %></a>
<% } %>
<input id="switch_default" type="checkbox" class="switch_default">
<label for="switch_default" class="toggleBtn"></label>
</div>
</div>
</nav>

<%# mobile %>
<nav class="navbar-mobile" id="nav-mobile">
<div class="container">
<div class="navbar-header">
<div>
<a href="<%- config.root %>"><%= theme.navname %></a><a id="mobile-toggle-theme">·&nbsp;Light</a>
</div>
<div class="navbar-mobile-right">
<% var type = 'mobile' %>
<%- partial('_partial/search', { name: type }) %>
<div class="menu-toggle" onclick="mobileBtn()">&#9776; 目录</div>
</div>

</div>
<div class="menu" id="mobile-menu">
<% for (var i in theme.nav){ %>
<a class="menu-item" href="<%- url_for(theme.nav[i]) %>"><%= i %></a>
<% } %>
</div>
</div>
</nav>
  1. 添加搜索框的js
    在/themes/Chic/layout/_pluguin/下新建文件search.ejs,并写入以下代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
<script>
function searchToggle() {
const width = $(document.body).width()
if(width > 479) {
return;
}
const search = $('.search');
const searchForm = $('.form-search')

if(!search.hasClass("mobile-search")) {
search.addClass("mobile-search");
} else {
search.removeClass("mobile-search");
}
}

function search(searchInputEl, formEl, flag) {
const path = "<%= config.root %>" + "<%= config.search.path %>"; // 可以在public 下查看这个search.json
$(formEl).submit(function(e){
e.preventDefault();
let target = null
if(searchInputEl == null) {
const screenWidth = $(document.body).width();
target = screenWidth > 479 ? $('#pc-search-input') : $('#mobile-search-input');
console.log(target);
} else {
target = $(searchInputEl)
}

if(!flag && target.val() === '') {
return ;
}

$("#u-search").fadeIn(500, function() {
$("body > .wrapper").addClass("modal-active");

$.ajax({
url: path,
dataType: "json",
beforeSend: function (xhr) {
$input = target.val();
$(".form-input").val($input);
const loadingBar = $('.search-loading-bar')
loadingBar.css({
width:'100%',
display: 'block'
});
},
success: function( datas ) {
console.log(datas);
const $resultPanel = $(".modal-body")[0];
let str = `<ul class="modal-results">`;
var keywords = $(".form-input").val().trim().toLowerCase().split(/[\s\-]+/);
$resultPanel.innerHTML = "";
let hasResult = false
let text = `<div class="no-result">找不到与关键词相关的内容....</div>`;

if ($(".form-input").val().trim().length <= 0) {
// 没有结果
$resultPanel.innerHTML = text;
return;
}
datas.forEach(function (data, index) {
var isMatch = true;
if (!data.title || data.title.trim() === '') {
data.title = "Untitled";
}
var data_title = data.title.trim().toLowerCase();
var data_content = data.content && data.content.trim().replace(/<[^>]+>/g, "").toLowerCase() || '';
var data_url = data.url;
var index_title = -1;
var index_content = -1;
var first_occur = -1;
// only match artiles with not empty contents
if (data_content !== '') {
keywords.forEach(function (keyword, i) {
index_title = data_title.indexOf(keyword);
index_content = data_content.indexOf(keyword);

if (index_title < 0 && index_content < 0) {
isMatch = false;
} else {
hasResult = true
if (index_content < 0) {
index_content = 0;
}
if (i == 0) {
first_occur = index_content;
}
}
});
} else {
isMatch = false;
}
// show search results
if (isMatch) {
str += `<li class='result-item'><a href='${data_url}' class='result-item-detail'> <span class="title">${data_title}</span>`;
var content = data.content.trim().replace(/<[^>]+>/g, "");
if (first_occur >= 0) {
// cut out 200 characters
var start = first_occur - 40;
var end = first_occur + 160;

if (start < 0) {
start = 0;
}

if (start == 0) {
end = 200;
}

if (end > content.length) {
end = content.length;
}

var match_content = content.substring(start, end);

// highlight all keywords
keywords.forEach(function (keyword) {
var regS = new RegExp(keyword, "gi");
match_content = match_content.replace(regS, `<em class="search-keyword">${keyword}</em>`);
});

str += `<span class="content"> ${match_content} ...</span></a>`;
}
str += "</li>";
}
});
str += "</ul>";
if(hasResult) {
$resultPanel.innerHTML = str;
} else {
$resultPanel.innerHTML = text;
}

},
complete: function() {
setTimeout(() => {
const loadingBar = $('.search-loading-bar')
loadingBar.css({
width:'0%',
display: 'none'
});
}, 300)
}
});
})

});
}

$(document).ready(function() {
$('.modal-close').click(function () {
$("#u-search").fadeOut();
$("body > .wrapper").removeClass("modal-active")
})

$('.modal-overlay').click(function() {
$("#u-search").fadeOut();
$("body > .wrapper").removeClass("modal-active")
})
search(null, ".form-search", false)
search("#u-search-modal-form .form-input", ".u-search-modal-form", true)
})
</script>
  1. 启动搜索框的js
    打开/themes/Chic/layout_partial/head.ejs,尾行写入以下代码:
1
2
3
4
5
<%# search %>

<% if(config.search && config.search.enable ) { %>
<%- partial('_plugins/search.ejs') %>
<% } %>
The End
以上就是整个搜索功能的加入的过程

Ref:

  1. Chou_Bill
  2. Chic主题